package com.ktjiaoyu.controller;

import com.alibaba.fastjson2.JSON;
import com.ktjiaoyu.entity.SysRole;
import com.ktjiaoyu.entity.SysUser;
import com.ktjiaoyu.service.SysRoleService;
import com.ktjiaoyu.service.SysUserService;
import com.ktjiaoyu.service.UploadService;
import com.ktjiaoyu.service.impl.SysRoleServiceImpl;
import com.ktjiaoyu.utils.Constants;
import com.ktjiaoyu.utils.Page;
import jakarta.servlet.annotation.MultipartConfig;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/main/user")
public class SysUserController extends BaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(SysUserController.class);
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    @Qualifier("toLocalUploadService")
    private UploadService uploadService;

    @RequestMapping("/page")
    public String page(Model model, SysUser condition, @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {
        Page<SysUser> page = null;
        try {
            //查询用户的分页信息
            page = sysUserService.findPage(condition, pageNo, pageSize);
            //查询所有的角色信息
            List<SysRole> roleList = sysRoleService.findAll();
            //将分页数据/角色信息/查询条件放入model中
            model.addAttribute("pageInfo", page);
            model.addAttribute("roleList", roleList);
            model.addAttribute("condition", condition);
        } catch (Exception e) {
            LOGGER.error("SysUserController中page方法执行发生错误", e);
            throw new RuntimeException(e);
        }
        return "user/page";
    }

    @GetMapping("/save")
    public String toSave(Model model) {
        List<SysRole> roleList = null;
        try {
            //查询所有的角色信息
            roleList = sysRoleService.findAll();
            //将角色信息放入model中 有角色下拉框需要数据
            model.addAttribute("roleList", roleList);
            //回显数据时需要sysUser,给个空对象避免出错
            model.addAttribute("sysUser", new SysUser());
        } catch (Exception e) {
            LOGGER.error("SysUserController中toSave方法执行发生错误", e);
            throw new RuntimeException(e);
        }
        return "user/save";
    }

    @PostMapping("/save")
    public String doSave(SysUser sysUser, MultipartFile idPic, MultipartFile workPic) {
        //允许上传图片后缀
        String[] allowImageExt = {"jpg", "jpeg", "png", "gif", "bmp"};
        try {
            //上传身份证图片
            if (idPic != null) {
                String idPicPath = uploadService.uploadFile(idPic, allowImageExt);
                sysUser.setIdPicPath(idPicPath);
            }
            //上传工作照
            if (workPic != null) {
                String workPicPath = uploadService.uploadFile(workPic, allowImageExt);
                sysUser.setWorkPicPath(workPicPath);
            }
            //通过父类的session方法获取登录用户,由于泛型自动转换,无需强转
            SysUser loginUser = session(Constants.SESSION_USER);
            if (sysUser.getId() == null) {
                //添加用户,关联创建用户为当前登录用户
                sysUser.setCreatedUserId(loginUser.getId());
                sysUser.setCreatedTime(new Date());
            } else {
                sysUser.setUpdatedUserId(loginUser.getId());
                sysUser.setUpdatedTime(new Date());
            }
            //新增或修改用户
            boolean ok = sysUserService.saveOrUpdate(sysUser);
            if (ok) {
                //重定向到用户列表页面
                return redirect("/main/user/page");
            }
        } catch (Exception e) {
            LOGGER.error("SysUserController中doSave方法执行发生错误", e);
            throw new RuntimeException(e);
        }
        return "user/save";
    }

    @GetMapping("/view/{id}")
    public String view(@PathVariable("id") Long id, Model model) {
        SysUser sysUser = null;
        try {
            //根据id查询用户信息
            sysUser = sysUserService.findById(id);
            model.addAttribute("sysUser", sysUser);
        } catch (Exception e) {
            LOGGER.error("SysUserController中view方法执行发生错误", e);
            throw new RuntimeException(e);
        }
        return "user/view";
    }

    //    @GetMapping(value = "/{id}/view",produces = "application/json;charset=utf-8")
    @GetMapping(value = "/{id}/view")
    @ResponseBody
    public Map ajaxView(@PathVariable("id") Long id) {
        HashMap<String, Object> resultMap = new HashMap<>();
        SysUser info = null;
        try {
            //根据id查询用户信息
            info = sysUserService.findById(id);
            if (info != null) {
                resultMap.put("code", 200);
                resultMap.put("data", info);
            } else {
                resultMap.put("code", 500);
            }
        } catch (Exception e) {
            LOGGER.error("SysUserController中ajaxView方法执行发生错误", e);
            throw new RuntimeException(e);
        }
        return resultMap;
    }

    @ResponseBody
    @DeleteMapping("/del/{id}")
    public Map del(@PathVariable("id") Long id) {
        HashMap<String, Object> resultMap = new HashMap<>();
        try {
            //根据id删除用户信息
            boolean ok = sysUserService.deleteById(id);
            if (ok) {
                resultMap.put("code", 200);
                resultMap.put("data", "数据删除成功");
            } else {
                resultMap.put("code", 500);
            }

        } catch (Exception e) {
            LOGGER.error("SysUserController中de方法执行发生错误", e);
            throw new RuntimeException(e);
        }
        return resultMap;
    }


    @GetMapping("/edit")
    public String toEdit(Model model, @RequestParam("id") Long id) {
        SysUser sysUser = null;
        List<SysRole> roleList = null;
        try {
            //根据id查询用户信息
            sysUser = sysUserService.findById(id);
            roleList = sysRoleService.findAll();
            model.addAttribute("sysUser", sysUser);
            model.addAttribute("roleList", roleList);
        } catch (Exception e) {
            LOGGER.error("SysUserController中toEdit方法执行发生错误", e);
            throw new RuntimeException(e);
        }
        return "user/save";
    }

    @ResponseBody    //返回json数据给前端,不走视图解析器
    @GetMapping("/accountExist")
    public String accountExist(@RequestParam("account") String account) {
        LOGGER.debug("检查用户名account={}的用户是否存在", account);
        HashMap<String, Object> resultMap = new HashMap<>();
        if (StringUtils.isEmpty(account)) {
            resultMap.put("exist", 0);
        } else {
            try {
                SysUser sysUser = sysUserService.findByAccount(account);
                if (sysUser != null) {
                    resultMap.put("exist", 1);
                } else {
                    resultMap.put("exist", 0);
                }
            } catch (Exception e) {
                LOGGER.error("SysUserController中accountExist方法执行发生错误", e);
                resultMap.put("error", "出现异常,请联系管理员");
            }
        }
        return JSON.toJSONString(resultMap);
    }

}
